package com.application.magazine;

import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.application.magazine.bookitem.BookmarksAdapter;
import com.application.magazine.bookitem.BookshelfView;
import com.devspark.appmsg.AppMsg;
import com.roscopeco.ormdroid.Entity;

public class BookMarkFragment extends Fragment {
	private BookshelfView bsView;
	public BookMarkFragment() {

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		System.gc();
		View v = null;
		v = inflater.inflate(R.layout.my_book_layout, null);
		bsView = (BookshelfView) v.findViewById(R.id.bookShelfGrid);
		new BookmarksTask(bsView).execute();
		return v;
	}
	
	class BookmarksTask extends AsyncTask<String, Void, List<Bookmarks>> {
		ProgressDialog pDialog;
		private BookshelfView view;

		public BookmarksTask(BookshelfView view) {
			super();
			this.view = view;	
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(getActivity());
			pDialog.setMessage(GlobalVariable.LOADING_DIALOG_MESSAGE);
			pDialog.show();
		}

		@Override
		protected List<Bookmarks> doInBackground(String... params) {

			InputStream is = null;
			List<Bookmarks> listTest = Entity.query(Bookmarks.class).executeMulti();
			Collections.sort(listTest,Collections.reverseOrder(new ComparableBookmark()));
			return listTest;
		}

		@Override
		protected void onPostExecute(List<Bookmarks> result) {
			super.onPostExecute(result);
			if (null != pDialog && pDialog.isShowing()) {
				pDialog.dismiss();
			}

			if (result != null) {
				view.setAdapter(new BookmarksAdapter(getActivity().getApplicationContext(), result, getActivity()));
			} else {
				AppMsg appMsg = AppMsg.makeText(getActivity(), "An error occured.", AppMsg.STYLE_ALERT);
				appMsg.setLayoutGravity(Gravity.BOTTOM);
				appMsg.show();
				//(Toast.makeText(context, "An error occured.", Toast.LENGTH_LONG)).show();
			}

		}

	}
}
